import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
const _axios = axios.create({
  baseURL: process.env.VUE_APP_URL
})
_axios.interceptors.request.use(
  (config) => {
    config.headers.token = store.state.user.token
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
_axios.interceptors.response.use(
  (res) => {
    if (res.data.code === 200) {
      return res.data
    } else if (res.data.code === 206) {
      // token超时了
      store.commit('user/LOGOUT')
      Message.error('登陆超时了')
      router.push('/login')
    } else {
      Message.error(res.data.message)
      return Promise.reject(new Error(res.data.message))
    }
  },
  (error) => {
    if (error.response.status === 401) {
      // token超时了
      store.commit('user/LOGOUT')
      Message.error('登陆超时了')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)
export default _axios
